<?php

namespace Apps\Manage\Controllers;
use Apps\Common\Enum\ActivityState;
use Apps\Common\Enum\SearchDataType;
use Apps\Common\Libs\SearchASync;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\Activity;
use Apps\Common\Models\ActivityBeautyParlor;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use Apps\Common\Models\SysOpenCity;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Enum\ActivityPositionState;
use Apps\Common\Enum\PositionState;
use Apps\Common\Enum\Position;
use Apps\Common\Models\ActivityComment;
use Phalcon\Mvc\Model;
use Apps\Common\Models\UserBase;
use PhalconPlus\Common\Util;

/**
 * 活动管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class ActivityController extends BaseController {
	public function initialize() {
		parent::initialize ();
		$this->setMainNav ( 'activity' );
	}
	public function indexAction() {
		$this->response->redirect ( 'activity/list' );
	}
	
	/**
	 * 活动列表
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function listAction() {
		$this->setLeftNav ( 'list' );
		$req = $this->request;
		$page = intval ( $req->getQuery ( 'page', null, 1 ) );
		$page = $page > 0 ? $page : 1;
		$limit = $this->pageNavLimit;
		$offset = $limit * ($page - 1);		
		$filterCity = intval ( $req->getQuery ( 'filterCity', null, -10000 ) );
		$activity_state = intval($req -> getQuery('activity_state',null,-10000));
		$activity_title = $req -> getQuery('activity_title');
		$activity_time = $req->getQuery('activity_time');
		$timeSlotarr=explode("至",$activity_time);
		
		
		$columns = [ 
				'activity_id',
				'city_name',
		        'create_user', 
				'activity_title',
				'activity_state',
				'activity_start_time',
				'activity_end_time',
				'activity_end_time - NOW() AS ts',
		        'activity_start_time - NOW() AS stime',
				'posion_banner',
				'out_link' 
		];
		$where = [ ];
		$bind = [ ];
		$medal = [ ];
		//获取当前时间
		$date = date("Y-m-d H:i:s");
		//通过状态筛选数据
	   if ($activity_state > - 10000) {
	       /* $where [] = 'activity_state = :state:';
	       $bind ['state'] = $activity_state; */
			//已结束数据：状态为2，或者结束时间小于当前时间
			if($activity_state == 2){
				$where [] = "(activity_state = 2 or activity_end_time < '$date')";
			}else{
				//正常数据：状态为1，且结束时间大于当前时间
				if($activity_state == 1){
					$where [] = " (activity_state = $activity_state and activity_end_time >= '$date') ";
				}
				//待发布数据：状态为0，且结束时间大于当前时间
				if($activity_state == 0){
					//$where [] = "activity_end_time >= '$date'";
					$where [] = " activity_state = $activity_state ";
				}
			}
			
		}
		//通过城市筛选数据
		if ($filterCity > - 10000) {
			$where [] = 'Apps\Common\Models\Activity.city_id = :city:';
			$bind ['city'] = $filterCity;
		}
		
		//通过活动标题筛选数据
		if($activity_title != ''){
		    $where[]="activity_title like '%".$activity_title."%'";
		    $this->view->setVar("activity_title",$activity_title);
		}
		//通过活动周期筛选数据
		if($activity_time != ''){
			$where[]="activity_start_time > '".$timeSlotarr[0]."'";
			$where[]="activity_end_time < '".$timeSlotarr[1]."'";
		}
		
		//$where [] = 'activity_state > -1';
		
		
		
		$whereStr = implode ( ' AND ', $where );
			 
		$query = Activity::query ()
			->columns ( $columns )
			->leftJoin ( 'Apps\Common\Models\SysOpenCity', 'soc.city_id=Apps\Common\Models\Activity.city_id', 'soc' ); 
		
		
		if (! empty ( $whereStr )) {
			
			$query = $query->where ( $whereStr );
		}
		
		if (count ( $bind ) > 0) {
			$query = $query->bind ( $bind );
		}
		
		$data = $query->orderBy ( 'activity_update_time DESC,activity_id DESC' )->limit ( $limit, $offset )->execute () -> toArray();
		foreach ($data as $k => $v){
		     if(empty($data[$k]['activity_end_time'])){
		        $data[$k]['ts'] = 1;
		    } 
		}
		// 总数
		$total = Activity::count ( [ 
				'conditions' => $whereStr,
				'bind' => $bind 
		] );
		$this->view->setVar ( 'filterCity', $filterCity );
		$this -> view -> setVar('activity_state', $activity_state);
		$this->view->setVar("activity_time",$activity_time);
		
		$this->view->setVar ( 'total', $total );
		$this->view->setVar ( 'page', $page );
		$this->view->setVar ( 'limit', $limit );
		
		$this->view->setVar ( 'data', $data );
		
		$this->view->setVar ( 'openCity', SysOpenCity::find ('city_state = 1') );
		$this->view->setVar ( 'stateList', ActivityState::valuesExplain () );
	}
	/**
	 * 添加活动
	 * @date: 2016年1月5日 
	 * @author: chenxiaolin
	 */
	public function addAction() {
		$this->setLeftNav ( 'add' );
		$req = $this->request;
		$response = new ResponseResult();
		$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
		$response->callbackJavascriptTag = true;
		
		if (! $req->isPost ()) {
			// 根据城市ID和广告位查询活动信息
			$page = intval ( $req->getQuery ( 'page', null, 1 ) );
			$page = $page > 0 ? $page : 1;
			$limit = $this->pageNavLimit;
			$offset = $limit * ($page - 1);
			
			//1.1版本中：通过城市、广告位筛选活动
			/* $filterCity = intval ( $req->getQuery ( 'filterCity', null, 0 ) );
			$posion_banner = intval ( $req->getQuery ( 'posion_banner', null, 0 ) );
			if ($posion_banner > 0 && $filterCity > 0) {
				$data = Activity::query ()
				->where ("posion_banner = $posion_banner AND city_id = $filterCity AND activity_state = 1")
				->execute ();
			}			
			$this->view->setVar ( 'filterCity', $filterCity );
			$this->view->setVar ( 'posion_banner', $posion_banner );
			$this->view->setVar ( 'data', $data );
			$this->view->setVar ( 'positionList', Position::valuesExplain () ); */
			
			$this->view->setVar ( 'openCity', SysOpenCity::find ('city_state = 1') );
			return;
		}else{			
			
			$type = intval($req->getPost('activity_type', null, 0));
	  		$title = $req->getPost('activity_title', null, '');
	  		$city = $req->getPost('city');	  		
	  		$intro = $req->getPost('activity_intro', null, '');
	  		$link = $req->getPost('out_link', null, '');
	  		$views = intval($req -> getPost('views',null,0));
 		
	  		//1.1版本中：查询数据
	  		/* $posion = intval($req->getPost('posion', null, 0));
	  		 * $time = $req->getPost('activity_time', null, '');
	  		$data2 = Activity::findFirst ("posion_banner = $posion AND city_id = $cityId AND activity_state = 1"); 	  			
	  		$timeArr = explode(' 至 ', $time);*/	
	  		
	  		
	  		// 判断空数据
	  		 if($type <=0 || empty($city) || empty($title)) {
	  			 $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
	  			 return $response;
	  		} 
	  		
	  		//判断是图文，还是外链地址
	  		if($type == 1 && empty($intro)){
	  		    $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写图文介绍！' );
	  		    return $response;
	  		}
	  		if($type == 2 && empty($link)){
	  		    $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写外链地址！' );
	  		    return $response;
	  		}
	  		
	  		//判断外链地址是否合法
	  		if($type == 2 && !Util::CheckUrl($link)){
	  		    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '外链地址不合法！');
	  		    return $response;
	  		}
	  		//1.1版本中：修改查询出来的数据
	  		 /* if($data2){//有数据，修改
	  			//保存封面
	  			$uploadFile = new UploadPic();
	  			$uploadFile->request = $req;
	  			$cover = $uploadFile->activityCover();
	  			if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
	  				if($_FILES['activity_cover']['error'] == 1) {
	  					$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了2M！');
	  					return  $response;
	  				}
	  			}
	  			$cover = $cover[0];	  			
	  			if(empty($cover)){		  				
	  				$cover = $data2 -> activity_cover;
	  			} 
	  			//判断是图文，还是外链地址
	  			if($type == 1 && empty($intro)){
	  				$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写图文介绍！' );
	  				return $response;
	  			}
	  			if($type == 2 && empty($link)){
	  				$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请填写外链地址！' );
	  				return $response;
	  			}
	  				
	  			
	  			$data2->update([
	  				'activity_title'=>$title, 
	  				'activity_type' => $type,
	  				'activity_intro' => $intro,
	  				'out_link' => $link,
	  				'activity_start_time' => $timeArr[0],
	  				'activity_end_time' => $timeArr[1],
	  				'activity_cover' => $cover	  						  					
	  			]);	
	  			$response->sendResult($data2 -> activity_id);
	  			return $response;
	  		}else{}//没数据，添加 */
	  			
	  			//保存封面
	  			$uploadFile = new UploadPic();
	  			$uploadFile->request = $req;
	  			$cover = $uploadFile->activityCover();	
	  			if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
	  				if($_FILES['activity_cover']['error'] == 1) {
	  					$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
	  					return  $response;
	  				}else {
	  					$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '活动封面必须上传！');
	  					return  $response;
	  				} 
	  			}
	  			
	  			$cover = $cover[0]; 
	  			
	  			
	  			
                foreach ($city as $k => $v){
                    $activity = new Activity();
                    $activity -> activity_type = $type;
                    $activity -> activity_title = $title;
                    $activity -> activity_cover = $cover;
                    $activity -> views = $views;
                    $activity -> city_id = $v;
                    $activity -> activity_intro = $intro;
                    $activity -> create_user = $this -> operator -> name;
                    /* $activity -> activity_start_time = $timeArr[0];
                    $activity -> activity_end_time = $timeArr[1]; */
                    $activity -> activity_addtime = date("Y-m-d H:i:s");
                    $activity -> activity_update_time = date("Y-m-d H:i:s");
                    $activity -> posion_banner = 1;
                    $activity -> out_link = $link;
                    $activity -> activity_state = 0;
                    $id = $activity->save();
                    if($id === false) {
                        $this->databaseErrorLog($activity);
                        $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
                    } else {
                        SearchASync::Instance()->noticeSync($activity->activity_id, SearchDataType::Activity);
                        $response->sendResult($id);
                    }
                }	  			
	  		     return $response;
	  		
	  			 	
		}
	}
	
	
	
	
	
	
	
	
	/**
	 * 添加活动1.0版本
	 * 
	 * @return ResponseResult
	 */
	/*
	 * public function addAction()
	 * {
	 * $this->setLeftNav('add');
	 * $req = $this->request;
	 * if(!$req->isPost()) {
	 * $this->view->setVar('openCity', SysOpenCity::find());
	 * return;
	 * }
	 *
	 * $response = new ResponseResult();
	 * $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
	 * $response->callbackJavascriptTag = true;
	 *
	 * $type = intval($req->getPost('activity_type', null, 0));
	 * $title = $req->getPost('activity_title', null, '');
	 * $cityId = intval($req->getPost('city_id', null, 0));
	 * $time = $req->getPost('activity_time', null, '');
	 * $intro = $req->getPost('activity_intro', null, '');
	 *
	 * // 判断空数据
	 * if($type <=0 || $cityId <= 0 || empty($title) || empty($time) || empty($intro)) {
	 * $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
	 * return $response;
	 * }
	 *
	 * // 保存封面
	 * $uploadFile = new UploadPic();
	 * $uploadFile->request = $req;
	 * $cover = $uploadFile->activityCover();
	 * if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
	 * if($_FILES['activity_cover']['error'] == 1) {
	 * $response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了2M！');
	 * } else {
	 * $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '封面必须上传！');
	 * }
	 * return $response;
	 * }
	 * $cover = $cover[0];
	 *
	 * $timeArr = explode(' 至 ', $time);
	 *
	 * $info = new Activity();
	 * $info->activity_type = $type;
	 * $info->activity_title = $title;
	 * $info->city_id = $cityId;
	 * $info->activity_intro = $intro;
	 * $info->activity_cover = $cover;
	 * $info->activity_start_time = $timeArr[0];
	 * $info->activity_end_time = $timeArr[1];
	 * if($info->save() == false) {
	 * $this->databaseErrorLog($info);
	 * $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
	 * } else {
	 * SearchASync::Instance()->noticeSync($info->activity_id, SearchDataType::Activity);
	 * $response->sendResult($info->activity_id);
	 * }
	 * return $response;
	 * }
	 */
	/**
	 * 查看活动回复列表
	 * @date: 2016年1月5日 
	 * @author: chenxiaolin
	 */
	public function commentListAction(){
	    $this -> setLeftNav('commentList');
	    $req = $this->request;
	    $page = intval ( $req->getQuery ( 'page', null, 1 ) );
	    $page = $page > 0 ? $page : 1;
	    $limit = $this->pageNavLimit;
	    $offset = $limit * ($page - 1);
	    
	    $activity_id = $req -> getQuery('id');
	    $user_name = $req -> getQuery('user_name');
	    $comment_content = $req -> getQuery('comment_content');
	    $addtime = $req->getQuery('addtime');
	    $timeSlotarr=explode("至",$addtime);
	    
	    
	    $columns = [
	        'comment_id',
	        'comment_content',
	        'addtime',
	        'user.user_nickname as user_name'
	    ];
	    $where = [ ];
	    $bind = [ ];
	    $medal = [ ];
	    //通过用户名筛选数据
	    if($user_name != ''){
	        $user = UserBase::query()
	           -> columns(['user_id'])
	           -> where("user_nickname like '%".$user_name."%'")
	           -> execute();
	           
	            foreach ($user as $k => $v){
	                $user_id .= $v['user_id'].',';
	            }
	            $user_id = rtrim($user_id, ",");
	            if(!empty($user_id)){
	               $where[]="comment_user_id in ( $user_id )";
	            }else{
	                $where[]="comment_user_id in ( 0 )";
	            }
	            $this->view->setVar("user_name",$user_name);
	    }
	    //通过评论内容筛选数据
	    if($comment_content != ''){
	        $where[]="comment_content like '%".$comment_content."%'";
	        $this->view->setVar("comment_content",$comment_content);
	    }
	    //通过评论时间筛选数据
	    if($addtime){
	        $where[]="addtime > '".$timeSlotarr[0]."'";
	        $where[]="addtime < '".$timeSlotarr[1]."'";
	        $this->view->setVar("addtime",$addtime);
	    }
	    
	    $where[] = "activity_id = $activity_id and state = 1"; 
	    
	    $whereStr = implode ( ' AND ', $where );
	    
	    
	    $query = ActivityComment::query ()
	    ->columns ( $columns )
	    ->leftJoin ( 'Apps\Common\Models\UserBase', 'user.user_id=Apps\Common\Models\ActivityComment.comment_user_id', 'user' );
	    
	    
	    if (! empty ( $whereStr )) {
	        	
	        $query = $query->where ( $whereStr );
	    }
	    
	    if (count ( $bind ) > 0) {
	        $query = $query->bind ( $bind );
	    }
	    
	    $data = $query->orderBy ( 'addtime DESC' )->limit ( $limit, $offset )->execute ();
	    /* var_dump($data);
	    exit;
	     */
	    // 总数
	    $total = ActivityComment::count ( [
	        'conditions' => $whereStr,
	        'bind' => $bind
	    ] );
	    
	    
	    $this->view->setVar ( 'total', $total );
	    $this->view->setVar ( 'page', $page );
	    $this->view->setVar ( 'limit', $limit );
	    
	    $this->view->setVar ( 'data', $data );
	    $this -> view -> setVar('activity_id', $activity_id);
	    
	}
	
	/**
	 * 删除活动回复
	 * @date: 2016年1月6日 
	 * @author: chenxiaolin
	 */
	public function setCommentStateAction(){
	    $req = $this->request;
	    if ($req->isPost ()) {
	        $id = intval ( $req->getPost ( 'id', null, 0 ) );
	        $activity_id = $req -> getPost('activity_id');
	        $state = intval ( $req->getPost ( 'state', null, - 10000 ) );
	        $info = ActivityComment::findFirst ( 'comment_id = ' . $id );
	        $activity = Activity::findFirst("activity_id = $activity_id");	        
	        if($info && $activity){
	            try {
	               $this -> db -> begin();
	               $info->update ( ['state' => $state] );
	               $comments = $activity -> comments - 1;
	               $activity -> update(['comments' => $comments]);
	               $this -> db -> commit(); 
	            } catch (Exception $e) {
	                $this -> db -> rollback();
	            }
	        }
	        return (new ResponseResult ())->sendResult ( 'ok' );
	    } else {
	        return (new ResponseResult ())->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
	    }
	}
	
	/**
	 * 跟新活动基础信息
	 * @date: 2016年1月5日 
	 * @author: chenxiaolin
	 */
	public function updateAction() {
		$this->setLeftNav ( 'update' );
		$req = $this->request;
		if (! $req->isPost ()) {
			$id = intval ( $req->getQuery ( 'id', null, 0 ) );
			$this->view->setVar ( 'id', $id );
			$this->view->setVar ( 'openCity', SysOpenCity::find () );
			$this->view->setVar ( 'info', Activity::findFirst ( 'activity_id = ' . $id ) );
			$this->view->setVar ( 'positionList', Position::valuesExplain () );
			return;
		}
		//修改
		$response = new ResponseResult ();
		$response->callback = $req->getPost ( 'callback', null, 'parent.setFormResult' );
		$response->callbackJavascriptTag = true;
		
		$id = intval ( $req->getPost ( 'activity_id' ) );
		if ($id < 1) {
			$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！' );
			return $response;
		}
		
		$type = intval ( $req->getPost ( 'activity_type', null, 0 ) );
		$title = $req->getPost ( 'activity_title', null, '' );
		$views = $req -> getPost('views');
		//$cityId = intval ( $req->getPost ( 'city_id', null, 0 ) );
		//$posion_banner = intval ( $req->getPost ( 'posion_banner', null, 0 ) );
		//$time = $req->getPost ( 'activity_time', null, '' );
		$intro = $req->getPost ( 'activity_intro', null, '' );
		$out_link = $req->getPost ( 'out_link', null, '' );
		
		// 判断空数据
		if ($type <= 0 || empty ( $title )) {
			$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！' );
			return $response;
		}
		//判断是图文，还是外链地址
		if($type == 1 && empty($intro)){
				$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！' );
				return $response;
		}
		if($type == 2 && empty($out_link)){
			$response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！' );
			return $response;
		}
		//判断外链地址是否合法
		if($type == 2 && !Util::CheckUrl($out_link)){
		    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '外链地址不合法！');
		    return $response;
		}
		//$timeArr = explode ( ' 至 ', $time );
		
		// 保存封面
		$uploadFile = new UploadPic ();
		$uploadFile->request = $req;
		$cover = $uploadFile->activityCover ();
		if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
			if($_FILES['activity_cover']['error'] == 1) {
				$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了2M！');
				return  $response;
			}
		}
		$cover = $cover[0];
		/* if ($cover == false || ! is_array ( $cover ) || count ( $cover ) == 0 || $cover [0] == false) {
			$cover = null;
		} else {
			$cover = $cover [0];
		} */
		
		// 保存基础数据
		$info = Activity::findFirst ( 'activity_id = ' . $id );
		$data = [ ];
		

		if ($info->activity_type != $type) {
			$data ['activity_type'] = $type;
		}
		if ($info->activity_title != $title) {
			$data ['activity_title'] = $title;
		}
		/* if ($info->city_id != $cityId) {//其他城市
			//判断广告位是否存在
			//$activity2 = Activity::findFirst('city_id = '.$cityId.' and posion_banner = '.$posion_banner);
			$activity2 = Activity::findFirst("city_id = $cityId and posion_banner = $posion_banner and activity_state in ('1','0')");
			if($activity2){//广告位已存在
				$response->sendError ( ResponseResultStatus::BUSINESS, '当前城市的此广告位已存在！' );
				return $response;
			}
			$data ['city_id'] = $cityId;
			$data ['posion_banner'] = $posion_banner;
			//推荐到其他城市时：活动状态设置
			$curTime = time();
			$startTime = strtotime($timeArr[0]);
			$endTime = strtotime($timeArr[1]);
			//1、活动开始时间大于当前时间：未发布--0
			if(($startTime - $curTime) > 0){
				$data ['activity_state'] = 0;
			}elseif(($endTime - $curTime) < 0 ){
				//2、活动结束时间小于当前时间：已结束--2
				$data ['activity_state'] = 2;
			}else{
				//3、当前时间大于开始时间，小于结束时间：正常--1
				$data ['activity_state'] = 1;
			}
					
		}else{//本城市			
			//根据城市id和广告位编号判断该城市的此广告位是否已存在
			if($info -> posion_banner != $posion_banner){
				//$activity = Activity::findFirst('city_id = '.$cityId.' and posion_banner = '.$posion_banner);
				$activity = Activity::findFirst("city_id = $cityId and posion_banner = $posion_banner and activity_state in ('1','0')");
				if($activity){//广告位已存在
					$response->sendError ( ResponseResultStatus::BUSINESS, '当前城市的此广告位已存在！' );
					return $response;
				}else{//广告位可用
					$data ['posion_banner'] = $posion_banner;
				}
			}			
			$curTime = time();
			$startTime = strtotime($timeArr[0]);
			$endTime = strtotime($timeArr[1]);
			//1、活动开始时间大于当前时间：未发布--0
			if(($startTime - $curTime) > 0){
				$data ['activity_state'] = 0;
			}elseif(($endTime - $curTime) < 0 ){
				//2、活动结束时间小于当前时间：已结束--2
				$data ['activity_state'] = 2;
			}else{
				//3、当前时间大于开始时间，小于结束时间：正常--1
				$data ['activity_state'] = 1;
			}
		} */
		if ($type == 1 && $info->activity_intro != $intro) {
			$data ['activity_intro'] = $intro;
			$data ['out_link'] = "";
		}
		if ($type == 2 &&$info->out_link != $out_link) {
			$data ['out_link'] = $out_link;
			$data ['activity_intro'] = "";
		}
		if ($info->views != $views) {
		    $data ['views'] = $views;
		}
		/* $data ['activity_start_time'] = $timeArr [0];
		$data ['activity_end_time'] = $timeArr [1]; */
		if ($cover != null) {
			$data ['activity_cover'] = $cover;
		}
		
		$data['activity_update_time'] = date("Y-m-d H:i:s");
			
		$info->update ( $data );
				
		SearchASync::Instance ()->noticeSync ( $id, SearchDataType::BeautyParlorService );

		$response->sendResult ( 'ok' );

		return $response;
	}
	
	/**
	 * 发布/结束活动
	 * @date: 2016年1月5日 
	 * @author: chenxiaolin
	 */
	public function setStateAction() {
		$req = $this->request;
		if(!$req -> isPost()){
		    $id = intval ( $req->getQuery( 'id', null, 0 ) );
		    $state = intval($req -> getQuery('state'));
		    $this -> view -> setVar('id', $id);
		    $this -> view -> setVar('state', $state);
		    $this->view->setVar("action",'/activity/setState');
		    return;
		}  
		if ($req->isPost ()) {
	   
		    $response = new ResponseResult();
		    $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
		    $response->callbackJavascriptTag = true;
		    
			$id = intval ( $req->getPost ( 'id', null, 0 ) );
			$state = intval ( $req->getPost ( 'state', null, - 10000 ) );
			$activity_start_time = $req -> getPost('activity_start_time');
			$activity_end_time = $req -> getPost('activity_end_time');
			//发布时：开始时间不能>=结束时间
			if($state == 1 && $activity_start_time >= $activity_end_time){
			    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '开始时间不能大于等于结束时间！');
			    return  $response;
			}
			 if (! in_array ( $state, [ 
					0,
					1,
					2 
			] )) {
				return $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
			} 
			$info = Activity::findFirst ( 'activity_id = ' . $id );
			
			//活动存在
			if($info){
				if($state == 1){//发布活动：修改活动的开始时间，结束时间，状态等信息
					$info -> update([
						'activity_state' => $state,
						'activity_update_time' => date('Y-m-d H:i:s'),
					    'activity_start_time' => $activity_start_time,
					    'activity_end_time' => $activity_end_time
					]);
					SearchASync::Instance ()->noticeSync ( $id, SearchDataType::Activity );
					return $response->sendResult ( 'ok' );
					
				}else {//结束活动
					$info->update ( [
						'activity_state' => $state,
					    'activity_update_time' => date('Y-m-d H:i:s')
					] );
					SearchASync::Instance ()->noticeSync ( $id, SearchDataType::Activity );
					return (new ResponseResult ())->sendResult ( 'ok' );
					/* $arr=[
                        'status'=>10000
                    ];
                    echo json_encode($arr);
                    exit; */
				}
			}
			
			
			
		} else {
			return $response->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
		}
	}
	
	/**
	 * 参与活动的美容院列表1.0版本
	 */
	public function bpListAction() {
		$req = $this->request;
		$id = intval ( $req->getQuery ( 'id', null, 0 ) );
		
		$columns = [ 
				'relation_id',
				'bp_id',
				'bp_name',
				'bp_cover',
				'bp_address',
				'bp_district',
				'FULL_NAME district',
				'bp_coordinate',
				'bp_tel',
				'bp_intro',
				'bp_state',
				'bp_is_sell',
				'bp_medal',
				'bp_addtime' 
		];
		
		$data = ActivityBeautyParlor::query ()->columns ( $columns )->leftJoin ( 'Apps\Common\Models\BeautyParlor', 'bp.bp_id = Apps\Common\Models\ActivityBeautyParlor.beauty_parlor_id', 'bp' )->leftJoin ( 'Apps\Common\Models\SysAreaZipDistrictPhonecode', 'K_ID=bp_district', 'area' )->where ( 'activity_id = :id: AND state > 0', [ 
				'id' => $id 
		] )->execute ();
		
		$this->view->setVar ( 'id', $id );
		$this->view->setVar ( 'data', $data );
	}
	
	/**
	 * 设置活动中的美容院状态1.0版本
	 * 
	 * @return $this|ResponseResult
	 */
	public function setBpStateAction() {
		$req = $this->request;
		if ($req->isPost ()) {
			$id = intval ( $req->getPost ( 'id', null, 0 ) );
			$state = intval ( $req->getPost ( 'state', null, - 10000 ) );
			if (! in_array ( $state, [ 
					- 1,
					0,
					1 
			] )) {
				return (new ResponseResult ())->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
			}
			$info = ActivityBeautyParlor::findFirst ( 'relation_id = ' . $id );
			if ($info) {
				$info->update ( [ 
						'state' => $state 
				] );
			}
			return (new ResponseResult ())->sendResult ( 'ok' );
		} else {
			return (new ResponseResult ())->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
		}
	}
	/**
	 * 1.0版本
	 * 
	 * @return $this|ResponseResult
	 */
	public function addBpAction() {
		$this->setLeftNav ( 'bp_list' );
		$req = $this->request;
		$id = intval ( $req->getQuery ( 'id', null, 0 ) );
		
		$page = intval ( $req->getQuery ( 'page', null, 1 ) );
		$page = $page > 0 ? $page : 1;
		$limit = $this->pageNavLimit;
		$offset = $limit * ($page - 1);
		
		$filterProvince = $req->getQuery ( 'filterProvince', null, '' );
		$filterCity = $req->getQuery ( 'filterCity', null, '' );
		$filterDistrict = intval ( $req->getQuery ( 'filterDistrict', null, - 10000 ) );
		
		$filterName = $req->getQuery ( 'filterName', null, '' );
		
		$columns = [ 
				'bp_id',
				'bp_name',
				'bp_cover',
				'bp_address',
				'bp_district',
				'FULL_NAME district',
				'bp_coordinate',
				'bp_tel',
				'bp_intro',
				'bp_state',
				'bp_is_sell',
				'bp_medal',
				'bp_addtime' 
		];
		$where = [ 
				'bp_state > 0' 
		];
		$bind = [ ];
		
		if (! ! $filterName) {
			$where [] = 'bp_name LIKE :fname:';
			$bind ['fname'] = '%' . $filterName . '%';
		}
		
		$districts = [ ];
		// 地区
		if ($filterDistrict > - 10000) {
			$where [] = 'bp_district = :district:';
			$bind ['district'] = $filterDistrict;
		} elseif (! empty ( $filterCity )) {
			// 获取所有城市的下级区县值
			$dids = SysAreaZipDistrictPhonecode::query ()->columns ( [ 
					'K_ID id' 
			] )->where ( 'P_NM = :province: AND C_NM = :city:', [ 
					'province' => $filterProvince,
					'city' => $filterCity 
			] )->execute ();
			foreach ( $dids as $d ) {
				$districts [] = $d->id;
			}
		} elseif (! empty ( $filterProvince )) {
			// 获取所有城市的下级区县值
			$dids = SysAreaZipDistrictPhonecode::query ()->columns ( [ 
					'K_ID id' 
			] )->where ( 'P_NM = :p:', [ 
					'p' => $filterProvince 
			] )->execute ();
			foreach ( $dids as $d ) {
				$districts [] = $d->id;
			}
		}
		
		if (count ( $districts ) > 0) {
			$where [] = 'bp_district IN(' . implode ( ', ', $districts ) . ')';
		}
		
		$whereStr = implode ( ' AND ', $where );
		
		$query = BeautyParlor::query ()->columns ( $columns )->leftJoin ( 'Apps\Common\Models\SysAreaZipDistrictPhonecode', 'K_ID=bp_district', 'area' );
		
		if (! empty ( $whereStr )) {
			$query = $query->where ( $whereStr );
		}
		
		if (count ( $bind ) > 0) {
			$query = $query->bind ( $bind );
		}
		
		$bpList = $query->orderBy ( 'bp_id DESC' )->limit ( $limit, $offset )->execute ()->toArray ();
		// 总数
		$total = BeautyParlor::count ( [ 
				'conditions' => $whereStr,
				'bind' => $bind 
		] );
		
		// 查看是否已经在此活动中
		// 查询所有参与的列表
		$joinList = ActivityBeautyParlor::find ( 'state > 0 AND activity_id = ' . $id );
		$joinBpIds = [ ];
		foreach ( $joinList as $j ) {
			$joinBpIds [] = strval ( $j->beauty_parlor_id );
		}
		for($i = 0; $i < count ( $bpList ); $i ++) {
			if (in_array ( strval ( $bpList [$i] ['bp_id'] ), $joinBpIds )) {
				$bpList [$i] ['bp_state'] = 1;
			} else {
				$bpList [$i] ['bp_state'] = 0;
			}
		}
		
		$this->view->setVar ( 'id', $id );
		$this->view->setVar ( 'filterProvince', $filterProvince );
		$this->view->setVar ( 'filterCity', $filterCity );
		$this->view->setVar ( 'filterDistrict', $filterDistrict );
		
		$this->view->setVar ( 'filterName', $filterName );
		
		$this->view->setVar ( 'total', $total );
		$this->view->setVar ( 'page', $page );
		$this->view->setVar ( 'limit', $limit );
		
		$this->view->setVar ( 'data', $bpList );
	}
	
	/**
	 * 添加美容院到活动中1.0版本
	 * 
	 * @return $this|ResponseResult
	 */
	public function bpJoinAction() {
		$req = $this->request;
		if ($req->isPost ()) {
			$id = intval ( $req->getPost ( 'id', null, 0 ) );
			$aid = intval ( $req->getPost ( 'aid', null, 0 ) );
			if ($id <= 0 || $aid <= 0) {
				return (new ResponseResult ())->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
			}
			$joinLog = new ActivityBeautyParlor ();
			$joinLog->activity_id = $aid;
			$joinLog->beauty_parlor_id = $id;
			$joinLog->state = 1;
			if ($joinLog->save ()) {
				return (new ResponseResult ())->sendResult ( 'ok' );
			} else {
				$this->databaseErrorLog ( $joinLog );
				return (new ResponseResult ())->sendError ( ResponseResultStatus::DATABASE_ERROR, '保存数据异常' );
			}
		} else {
			return (new ResponseResult ())->sendError ( ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常' );
		}
	}
	
}